×
☰ See All Chapters

JPA One-to-Many Unidirectional Association Mapping

One-to-many mapping is an association between one persistence object holding the collection of same related persistence objects. One persistence object mapped to many persistence objects. Tables of both the persistence classes will be related in database. As an example, one user can have many phone numbers. If one persistence object uses other and in back if other is not using the first persistence object then it becomes unidirectional.

JPA One-to-Many Unidirectional Association Mapping example

Now let us see how this mapping is done in persistence class by going through an example.  The following code shows how to do one-to-many mapping. We created two entities, Phoneuser and Phone. One Phoneuser holds many Phone. In the Phoneuser class we annotate the Phone field by @OneToMany annotation.

Database script (MySQL)

DROP TABLE PHONE;

COMMIT;

 

DROP TABLE PHONEUSER;

COMMIT;

 

CREATE TABLE PHONEUSER

(

USERID NUMERIC(10),

USERNAME VARCHAR(20) ,

USEREMAIL VARCHAR(20)

);

 

ALTER TABLE PHONEUSER ADD

(

PRIMARY KEY(USERID)

);

 

 

CREATE TABLE PHONE

(

PHONEID INT(10) PRIMARY KEY AUTO_INCREMENT,

PHONETYPE VARCHAR(10),

PHONENO NUMERIC(15),

USERID NUMERIC(10)

);

 

ALTER TABLE PHONE ADD

(

FOREIGN KEY(USERID) REFERENCES PHONEUSER (USERID)

)

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.java4coding</groupId>

        <artifactId>12M_UnidirectionalAssociationMapping</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>12M_UnidirectionalAssociationMapping</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

 

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

 

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="PhonePU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

Phone.java

package com.java4coding;

 

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name = "PHONE")

public class Phone {

 

        @Id

        @GeneratedValue(strategy = GenerationType.AUTO)

        private int phoneid;

 

        private String phonetype;

 

        private long phoneno;

 

        private int userid;

 

        public int getPhoneid() {

                return phoneid;

        }

        public void setPhoneid(int phoneid) {

                this.phoneid = phoneid;

        }

        public String getPhonetype() {

                return phonetype;

        }

        public void setPhonetype(String phonetype) {

                this.phonetype = phonetype;

        }

        public long getPhoneno() {

                return phoneno;

        }

        public void setPhoneno(long phoneno) {

                this.phoneno = phoneno;

        }

        public int getUserid() {

                return userid;

        }

        public void setUserid(int userid) {

                this.userid = userid;

        }

}

Phoneuser.java

package com.java4coding;

 

import java.util.List;

 

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.OneToMany;

import javax.persistence.Table;

 

@Entity

@Table(name="PHONEUSER")

public class Phoneuser {

 

        @Id

        private int userid;

 

        private String useremail;

       

        private String username;

       

        @OneToMany(cascade=CascadeType.ALL)

        @JoinColumn(name="USERID")

        private List<Phone> phoneTables;

 

        public int getUserid() {

                return userid;

        }

        public void setUserid(int userid) {

                this.userid = userid;

        }

        public String getUseremail() {

                return useremail;

        }

        public void setUseremail(String useremail) {

                this.useremail = useremail;

        }

        public String getUsername() {

                return username;

        }

        public void setUsername(String username) {

                this.username = username;

        }

        public List<Phone> getPhoneTables() {

                return phoneTables;

        }

        public void setPhoneTables(List<Phone> phoneTables) {

                this.phoneTables = phoneTables;

        }

}

Test.java

package com.java4coding;

 

import java.util.ArrayList;

import java.util.List;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

public class Test {

        public static void main(String[] args) {

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("PhonePU");

                EntityManager em = emf.createEntityManager();

 

                em.getTransaction().begin();

 

                Phoneuser phoneUser = new Phoneuser();

                phoneUser.setUsername("AAA");

                phoneUser.setUseremail("AAA@mail.com");

                phoneUser.setUserid(1);

               

                Phone phone1=new Phone();

                phone1.setPhoneno(111111);

                phone1.setPhonetype("Mobile");

                phone1.setUserid(1);

               

                Phone phone2=new Phone();

                phone2.setPhoneno(1111);

                phone2.setPhonetype("LandLine");

                phone2.setUserid(1);

               

                List<Phone> list = new ArrayList<>();

                list.add(phone1);

                list.add(phone2);

 

                phoneUser.setPhoneTables(list);

               

                em.persist(phoneUser);

                em.getTransaction().commit();

               

                em.getTransaction().begin();

                // User can access Phone Number

                Phoneuser u = em.find(Phoneuser.class, 1);

                System.out.println("userId is "+u.getUserid());

                System.out.println("UserName is "+u.getUsername());

                               

                List<Phone> list1 = u.getPhoneTables();

                for(Phone p:list1){

                        System.out.println("Phone Number is "+p.getPhoneno());

                        System.out.println("phone Type is "+p.getPhonetype());

                       

                }

 

                //Phone Number cannot access User Details

                /*Phone ph=(Phone)ses.load(Phone.class, new Integer(1));

                System.out.println("Phone Number is "+ph.getPhoneno());

                System.out.println("phone Type is "+ph.getPhonetype());

                */

        }

}

Project directory structure

jpa-one-to-many-unidirectional-association-mapping-0
 

Output:

Hibernate:

    insert

    into

        PHONEUSER

        (useremail, username, userid)

    values

        (?, ?, ?)

Hibernate:

    insert

    into

        PHONE

        (phoneno, phonetype, userid)

    values

        (?, ?, ?)

Hibernate:

    insert

    into

        PHONE

        (phoneno, phonetype, userid)

    values

        (?, ?, ?)

Hibernate:

    update

        PHONE

    set

        USERID=?

    where

        phoneid=?

Hibernate:

    update

        PHONE

    set

        USERID=?

    where

        phoneid=?

userId is 1

UserName is AAA

Phone Number is 111111

phone Type is Mobile

Phone Number is 1111

phone Type is LandLine

 


All Chapters
Author